package com.yt.base.controller.order;

import com.yt.base.controller.core.BaseController;
import com.yt.base.util.json.JacksonMapper;
import com.yt.core.MsgBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.order.api.interfaces.ProductTypeService;
import com.yt.order.api.model.ProductType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/order/productType")
public class ProductTypeController extends BaseController {

	@Autowired
	private ProductTypeService productTypeService;

	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("order/product/ProductTypeList");
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.addFilter(request.getParameterMap());
		List<ProductType> productTypeList = productTypeService.find(filter);
		int count = productTypeService.count(filter);
		mav.addObject("start", filter.getPagingBean().getStart());
		mav.addObject("limit", filter.getPagingBean().getPageSize());
		mav.addObject("total", count);
		mav.addObject("list", productTypeList);
		return mav;
	}

	@RequestMapping("/toAdd")
	public ModelAndView toAdd(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("order/product/ProductTypeAdd");
		return mav;
	}

	@RequestMapping("/toEdit")
	public ModelAndView toEdit(HttpServletRequest request,@RequestParam("id") Long id) {
		ModelAndView mav = new ModelAndView("order/product/ProductTypeAdd");
		ProductType productType = productTypeService.get(id);
		mav.addObject("bean", productType);
		return mav;
	}

	@RequestMapping("/del")
	@ResponseBody
	public Object multiDel(@RequestParam("id") Long id) {
		this.productTypeService.remove(new Long(id));
		return new MsgBean().returnMsg();
	}

	@RequestMapping("/get")
	@ResponseBody
	public String get(@RequestParam("id") Long id) {
		ProductType productType = productTypeService.get(id);
		return new JacksonMapper().toDataJson(productType);
	}


	@RequestMapping("/save")
	@ResponseBody
	public Object save(@RequestParam("id") Long id, @RequestParam("name") String name) {
		ProductType bean = null;
		if (id != null) {
			bean = productTypeService.get(id);
			bean.setName(name);
			productTypeService.update(bean);
		} else {
			bean = new ProductType();
			bean.setName(name);
			productTypeService.insert(bean);
		}
		return new MsgBean().returnMsg();
	}
}
